mod types;

pub use types::*;

use anyhow::{anyhow, Result};
use serde_json::{json, Value};
use std::fs::File;
use std::io::BufReader;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;

use super::config::PeerConfig;
use crate::utils::rrai_home_path;

pub async fn get_peer_config() -> Result<PeerConfig> {
    let config_path = rrai_home_path()?.join("config");

    let peer_config = if config_path.as_path().exists() {
        //从文件中读取配置
        let file = File::open(config_path.as_path())?;

        let mut buf_reader = BufReader::new(file);
        // 解析配置文件
        let mut buffer = Vec::new();
        buf_reader.read_to_end(&mut buffer)?;
        //
        let config_value: PeerConfig = serde_json::from_slice(&buffer)?;

        config_value
    } else {
        //默认配置并保存文件
        let default_config = PeerConfig::default();

        //保存文件
        let mut output = File::create(config_path.as_path())?;
        let content = json!(default_config).to_string();

        output.write_all(&content.as_bytes())?;

        default_config
    };
    //
    Ok(peer_config)
}
